<template>
  <div>
    <h1>API 状态监测</h1>
    <el-card style="padding-bottom: 20px;">
      <el-button style="float:right; margin-right: 15px" @click="uploadExcel()">上传</el-button>
      <el-icon style="float:left; margin-left: 15px" size="30" @click="dialogFormVisible=true"><CirclePlus /></el-icon>
      <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
          <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
            :on-change="handleFileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖拽文件(.xlsx)到此区域进行上传</div>
          </el-upload>
          <el-table :data="uploadedData" empty-text="正在加载" v-if="uploadedData.length">
            <el-table-column prop="接口名" label="接口名" />
            <el-table-column prop="站点路径" label="接口路径" />
            <el-table-column prop="接口描述" label="接口描述" />
            <el-table-column prop="接口状态" label="接口状态" />
            <el-table-column prop="测试数据" label="测试数据" />
          </el-table>
          <template #footer>
            <el-button @click="uploadData">上传</el-button>
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </template>
        </el-dialog>
    </el-card>
  </div>
  <el-table :data="apis" empty-text="正在加载" style="width: 120%">
    <el-table-column prop="name" label="接口名" />
    <el-table-column label="接口路径" width="200">
        <template v-slot="scope">
          <li
            :style="{ color: scope.row.state === 'true' ? 'green' : 'gray' }"
          >{{ scope.row.url }}</li>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="接口描述" />
      <el-table-column prop="state" label="接口状态" />
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <el-button size="small" @click="handleUpdate(scope.row)" type="primary">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
  </el-table>
  <!-- 编辑框 -->
  <el-dialog v-model="dialogFormVisible" :before-close="handleBeforeClose" title="接口信息" width="800">
      <el-form ref="formRef" :model="updateForm" :rules="rules">
        <el-form-item prop="name" label="接口名：">
          <el-input v-model="updateForm.name" />
        </el-form-item>
        <el-form-item prop="url" label="接口路径：">
          <el-input v-model="updateForm.url" />
        </el-form-item>
        <el-form-item prop="description" label="接口描述：">
          <el-input v-model="updateForm.description" />
        </el-form-item>
        <el-form-item prop="testData" label="接口测试数据：">
          <el-input v-model="updateForm.testData" />
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
    :current-page="queryParams.pageNum"
    :page-size="queryParams.pageSize"
    :page-sizes="[15, 30, 45]"
    :small="false"
    :disabled="false"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleNumChange"
  />
</template>

<script setup>
import {fetchInterface, updateInterface, deleteInterface, uploadInterface, createInterface} from "../../api/index"
import { nextTick, ref, reactive, onMounted, VueElement } from "vue";
import * as XLSX from "xlsx";

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  param: {
  }
});

//获得接口列表
const apis = ref([]); // 直接使用 ref 定义数组
let total = ref(0);

function getInterfaceList(){
  console.log("queryparam",queryParams);
  fetchInterface(queryParams)
  .then(res =>{
    console.log('res',res)
    apis.value = res.data.result.records; 
      total.value = res.data.result.total;
      console.log('queryParams.value', queryParams.param)
  })
  .catch(error=>{
    console.log("Error fetching apis list:",error);
  })
}

const handleSizeChange = val => {
  queryParams.value.pageSize = val;
  getUserList();
};

const handleNumChange = val => {
  queryParams.value.pageNum = val;
  getUserList();
};

//编辑功能
const dialogFormVisible = ref(false);
const formRef = ref();

const updateForm = ref({
  name: "",
  id: "",
  url: "",
  description: "",
  state:"",
  testData:""
});
const handleBeforeClose = (done) => {
  // 清空表单数据
  updateForm.value = {
    name: "",
    id: "",
    url: "",
    description: "",
    state:"",
    testData:""
  };
  done();
}
const handleUpdate = (rowData = {}) => {
  dialogFormVisible.value = true;
  console.log("rowData", rowData);
  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData);
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData);
    }
  });
};

const confirm = async () => {
  if (updateForm.value.id==''){
    console.log("添加添加")
    createInterface(updateForm.value)
    .then(response => {
      console.log('添加成功', response);
      dialogFormVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "添加成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
      getInterfaceList();
    })
    .catch(error => {
      console.error('添加失败', error);
      ElMessage({
        message: "添加失败",
        type: "error",
        duration: 1000
      });
    });
  }else {
    updateInterface(updateForm.value)
    .then(response => {
      console.log('上传成功', response);
      dialogFormVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
      getInterfaceList();
    })
    .catch(error => {
      console.error('修改失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
    });
  }
  
};

//删除
const deleteItem = async (id) => {
  try {
    await ElMessageBox.confirm('是否要该条数据', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    console.log(id);
    await deleteInterface(id);
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    });
  } catch (error) {
    // Handle cancel or error
  }
  getInterfaceList();
};

//上传文件
const fieldMapping = {
    "接口名":"name",
    "接口路径":"url",
    "接口描述":"description",
    "接口状态":"state",
    "测试数据":"testData"
}
const uploadedData = ref([])
const uploadDialogVisible = ref(false)

function uploadExcel() {
  uploadDialogVisible.value = true;
}

const handleFileChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    uploadedData.value = jsonData; // 将读取的数据保存到 uploadedData
  };

  reader.readAsArrayBuffer(file.raw);
};

const uploadData = async () => {
  let convertedData = convertFields(uploadedData)
  // 遍历 convertedData 数组，并将每个元素的 id 设置为 null
  convertedData.forEach(item => {
    item.id = 0;
  });
  console.log("convertedData",convertedData);
  uploadInterface(convertedData)
    .then(response => {
      console.log('上传成功', response);
      uploadedData.value = []; // 清空上传数据
      uploadDialogVisible.value = false; // 关闭弹窗
      ElMessage({
          message: "上传成功",
          type: "success",
          duration: 1000
        });
      // 可以根据需要进一步处理响应
    })
    .catch(error => {
      console.error('上传失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
      // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
      if (error.response) {
        // 请求已发出，服务器响应了状态码，且响应体
        console.error('服务器返回错误:', error.response.data);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        console.error('没有收到响应:', error.request);
      } else {
        // 发生了一些其他错误
        console.error('请求错误:', error.message);
      }
    });
};

const convertFields = (data) => {
  console.log("datadatadatadata",data.value);
  return data.value.map(row => {
    let convertedRow = {};
    Object.keys(row).forEach(key => {
      const englishKey = fieldMapping[key];
      if (englishKey) {
          convertedRow[englishKey] = row[key];
      }
    });
    return convertedRow;
  });
};

const selectedItems = ref([]); // 直接使用 ref 定义数组

function handleSelectionChange(selected) {
      selectedItems.value = selected; // 更新选中的项
      // console.log(selectedItems.value);
}

onMounted(() => {
  getInterfaceList();//获取接口数据

  //设置自动刷新（每隔  刷新一次）
  const refreshInterval = 300000;//刷新间隔为5分钟
  setInterval(() => {
    window.location.reload();//刷新页面
  },refreshInterval);
});

</script>

<style scoped>
/* 你可以根据需要自定义样式 */
li {
  font-size: 18px;
}
</style>
